# 自定义手机号路由转换器
class MobileConverter:
    regex = '1[3-9]\d{9}'

    def to_python(self, value):
        return str(value)

    def to_url(self, value):
        return str(value)


# 自定义jwt登入认证成功返回数据
def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'mobile': user.mobile,
        'avatar': user.avatar
    }


from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from .models import User


# 自定义类名并继承 ModelBackend
class ModelBackendCustom(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
        except User.DoesNotExist as e:
            return None

        if user.check_password(password):
            return user
